﻿using System.Collections.Generic;
using System.Linq;
using System.Web;
using Easy.Extend;
using Easy.Web.CMS;
using Easy.Web.CMS.Page;
using Easy.Web.CMS.Widget;
using Microsoft.Practices.ServiceLocation;
using System.Web.Mvc;
using Easy.CMS.List.Models;
using Easy.MetaData;
using System;
using Easy.Data;
using Easy.CMS.List.ViewModel;
using System.Net.Http;
using Newtonsoft.Json;
using Easy.Web.CMS.Helper;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using System.Text;
using System.Data;
using Easy.Web.CMS.Data;

namespace Easy.CMS.List.Service
{
    public class ListWidgetService : WidgetService<ListWidget>
    {
        public override WidgetPart Display(WidgetBase widget, ControllerContext controllerContext)
        {
            var currentWidget = widget as ListWidget;
            int pageIndex = controllerContext.RouteData.GetPage();
            var page = new Pagination { PageIndex = pageIndex, PageSize = currentWidget.PageSize ?? 10 };
       
            var viewModel =  new ListViewModel()
            {
                IsPageable = currentWidget.IsPageable,
                Widget = currentWidget,
                Pager = page,
                Columns = new List<string>(),
                JsonResult = string.Empty
            };

            string listId = currentWidget.ListId;
            string formCode = currentWidget.FormCode;
            string where = string.Empty;

            if (!string.IsNullOrEmpty(listId) && !string.IsNullOrEmpty(formCode))
            {
                StringBuilder select = new StringBuilder("[Id] ");
                HttpContent content = new StringContent(JsonConvert.SerializeObject(new
                {
                    CollectionName = "ListMobileField",
                    JsonData = string.Format("[{{\"ValueType\":\"String\",\"Name\":\"list_id\",\"Value\":\"{0}\",\"Operation\":\"EQ\"}}]", listId)
                }));
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var listDisplay = APIHelper.RunApiPost(Urls.ApiHost, "api/mp/list/findfirst/", content);
                if(!string.IsNullOrEmpty(listDisplay))
                {
                    var jsonObject = ((JObject)JsonConvert.DeserializeObject(listDisplay));
                    var displays = ((JArray)(JsonConvert.DeserializeObject(jsonObject["display_field"].ToString()))).ToList();
                    foreach(var v in displays)
                    {
                        string column = v["code"].ToString();
                        select.AppendFormat(", [{0}]",column);
                        viewModel.Columns.Add(column);
                    }

                    content = new StringContent(JsonConvert.SerializeObject(new
                    {
                        CollectionName = "DefineCondition",
                        JsonData = string.Format("[{{\"ValueType\":\"String\",\"Name\":\"list_id\",\"Value\":\"{0}\",\"Operation\":\"EQ\"}}]", listId)
                    }));

                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    var defineConditions = APIHelper.RunApiPost(Urls.ApiHost, "api/mp/list/findfirst/", content);

                    if (!string.IsNullOrEmpty(defineConditions))
                    {
                        jsonObject = ((JObject)JsonConvert.DeserializeObject(defineConditions));
                        List<Condition<object>> conditions = JsonConvert.DeserializeObject<List<Condition<object>>>(jsonObject["define"].ToString()); // ((List<Condition<object>>)(JsonConvert.DeserializeObject(jsonObject["define"].ToString()))).ToList();

                        where = conditions.GetCondition(WhereType.And);

                        Int32 rownumber = page.PageIndex * page.PageSize;

                        page.RecordCount = GetRecordCount(formCode,where);

                        string sql = @" select top {0} {1} from 
                               (
                                  select ROW_NUMBER() over( order by [createtime] desc, [Id] ) temprownumber,{1},[createtime] 
	                              from {2} where (1=1) {3}
                               ) t where (1=1) and t.temprownumber > {4}";
                        sql = string.Format(sql, page.PageSize, select, formCode, where, rownumber); //,InfoColumn
                        DataSet ds = YunPanDbHelper.Query(sql);
                        if (ds.HasData())
                        {
                            viewModel.JsonResult = ds.GetJsonString("yyyy-MM-dd HH:mm");
                        }
                    }
                }
               
            }
            return widget.ToWidgetPart(viewModel);
        }

        /// <summary>
        /// 获取总数量
        /// </summary>
        private Int32 GetRecordCount(string formCode, string where)
        {
            string result = string.Empty;
            string sql = string.Format("select count(1) from {0} where (1=1) {1}", formCode,where);
            DataSet ds = YunPanDbHelper.Query(sql);
            if (ds.HasData() && ds.Tables[0].Rows.Count>0)
            {
               result = ds.Tables[0].Rows[0][0].ToStringIgnoeNull();
            }
            return string.IsNullOrEmpty(result) ? 0 : Int32.Parse(result);
        }
    }
}